import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:nft_shop/box/page/box_page.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';
import 'package:nft_shop/main.dart';
import 'package:nft_shop/market/page/drawer_screen_page.dart';
import 'package:nft_shop/market/page/market_page.dart';
import 'package:nft_shop/my/page/my_page.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/sift/conteroller/index_conteroller.dart';
import 'package:nft_shop/sift/model/models.dart';
import 'package:nft_shop/sift/page/sift_page.dart';
import 'package:nft_shop/sift/search/search_list_page.dart';
import 'package:nft_shop/sift/view/app_update_view.dart';
import 'package:nft_shop/util/image_utils.dart';
import 'package:nft_shop/util/other_utils.dart';
import 'package:nft_shop/widgets/double_tap_back_exit_app.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:package_info/package_info.dart';

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with WidgetsBindingObserver {
  static const double _imageSize = 22.0;

  ///page
  final PageController _pageController = PageController();

  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  ///pageList
  late List<Widget> _pageList;

  ///BottomItem
  List<BottomNavigationBarItem>? _list;

  ///ItemTitle
  final List<String> _appBarTitles = [
    "精选",
    "市场",
    "盲盒",
    "我的",
  ];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance!.addObserver(this);
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      /// 预先缓存剩余切换图片
      _preCacheImage();
    });

    if (kReleaseMode) {
      //
      upgrade();
    }

    eventBus.on<String>().listen((it) {
      if (it == "logout") {
        _pageController.jumpToPage(0);
      }
    });
    initData();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance!.removeObserver(this); //添加观察者
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print("--" + state.toString());
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        print("监听--处于这种状态的应用程序应该假设它们可能在任何时候暂停。");
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        print("监听--应用程序可见，前台");
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        print("监听--应用程序不可见，后台");
        break;
    }
  }

  void _preCacheImage() {
    // precacheImage(ImageUtils.getAssetImage("tabbar/home_tabbar"), context);
  }

  void upgrade() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    AppInfo info = await ServiceRepository.upindex(
        Platform.isAndroid ? packageInfo.version : packageInfo.buildNumber);
    print("");
    if ((haveNewVersion(info.version!, packageInfo.version) &&
            Platform.isAndroid) ||
        (haveNewVersion(info.version!, packageInfo.buildNumber) &&
            Platform.isIOS)) {
      print("需要升级---");
      //需要升级
      Future.delayed(Duration.zero, () {
        Utils.showElasticDialog<void>(
          context: Get.context!,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AppUpdate(info);
          },
        );
      });
    }
  }

  ///初始化page
  void initData() {
    _pageList = [
      SiftPage(),
      MarketPage(
        onPressed: () {
          _scaffoldKey.currentState!.openEndDrawer();
        },
        onPressedSearch: (int index) {
          Get.to(SearchListPage(index));
        },
      ),
      BoxPage(),
      MyPage(),
    ];
  }

  ///TabbarItem
  List<BottomNavigationBarItem> _buildBottomNavigationBarItem() {
    if (_list == null) {
      const _tabImages = [
        [
          LoadAssetImage('tabbar_sift', width: _imageSize),
          LoadAssetImage(
            'tabbar_sift_select',
            width: _imageSize,
          ),
        ],
        [
          LoadAssetImage('tabbar_market', width: _imageSize),
          LoadAssetImage(
            'tabbar_market_select',
            width: _imageSize,
          ),
        ],
        [
          LoadAssetImage('tabbar_box', width: _imageSize),
          LoadAssetImage('tabbar_box_select', width: _imageSize),
        ],
        [
          LoadAssetImage('tabbar_my', width: _imageSize),
          LoadAssetImage(
            'tabbar_my_select',
            width: _imageSize,
          ),
        ],
      ];
      _list = List.generate(_tabImages.length, (i) {
        return BottomNavigationBarItem(
          icon: _tabImages[i][0],
          activeIcon: _tabImages[i][1],
          label: _appBarTitles[i],
        );
      });
    }
    return _list!;
  }

  @override
  Widget build(BuildContext context) {
    print("tabbar -- 刷新了");
    return GetBuilder<IndexConteroller>(
        id: IndexConteroller.TabbarItemWidget,
        builder: (logic) {
          return DoubleTapBackExitApp(
            child: Scaffold(
                key: _scaffoldKey,
                endDrawer: DrawerScreenPage(),
                bottomNavigationBar: BottomNavigationBar(
                  backgroundColor: Global.kTheme.colorBackground1,
                  items: _buildBottomNavigationBarItem(),
                  type: BottomNavigationBarType.fixed,
                  currentIndex: IndexConteroller.to.selectTab,
                  elevation: 5.0,
                  iconSize: 21.0,
                  selectedFontSize: 10,
                  unselectedFontSize: 10,
                  selectedItemColor: Global.kTheme.textPrimary0,
                  unselectedItemColor: Global.kTheme.textPrimary0,
                  onTap: (index) {
                    HapticFeedback.lightImpact();
                    if (index == 3 && !UserController.to.isLogin) {
                      Get.to(LoginPage());
                    } else {
                      _pageController.jumpToPage(index);
                    }
                  },
                ),
                body: PageView(
                  physics: const NeverScrollableScrollPhysics(), // 禁止滑动
                  controller: _pageController,
                  onPageChanged: (int index) {
                    IndexConteroller.to.changeTab(index);
                  },
                  children: _pageList,
                )),
          );
        });
  }

  bool haveNewVersion(String newVersion, String old) {
    if (newVersion == null || newVersion.isEmpty || old == null || old.isEmpty)
      return false;
    int newVersionInt, oldVersion;
    var newList = newVersion.split('.');
    var oldList = old.split('.');
    if (newList.length == 0 || oldList.length == 0) {
      return false;
    }
    for (int i = 0; i < newList.length; i++) {
      newVersionInt = int.parse(newList[i]);
      oldVersion = int.parse(oldList[i]);
      if (newVersionInt > oldVersion) {
        return true;
      } else if (newVersionInt < oldVersion) {
        return false;
      }
    }

    return false;
  }
}
